﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Cat.Helper
{
    class Web_helper
    {

        /// <summary>  
        /// Http同步Get异步请求  
        /// </summary>  
        /// <param name="url">Url地址</param>  
        /// <param name="callBackDownStringCompleted">回调事件</param>  
        /// <param name="encode">编码(默认UTF8)</param>  
        public void HttpGetAsync(string url, OpenReadCompletedEventHandler
             callBackReadStringCompleted = null, Encoding encode = null)
        {
            var webClient = new WebClient { Encoding = Encoding.UTF8 };
            webClient.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:56.0) Gecko/20100101 Firefox/56.0");
            webClient.Headers.Add("Accept-Language", "zh-cn");

            if (encode != null)
                webClient.Encoding = encode;

            if (callBackReadStringCompleted != null)
                webClient.OpenReadCompleted += callBackReadStringCompleted;
            try
            {
                webClient.OpenReadAsync(new Uri(url));
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }

        /// <summary>
        /// 辅助文件下载的类，成功返回true 失败返回false  需要文件路径
        /// </summary>
        /// <param name="url"></param>
        /// <param name="filepath"></param>
        /// <returns></returns>

        public bool FileDownloader(string url, string filepath)
        {
            new File_helper().File_existence(filepath);
            if ((filepath.Length + Path.GetFileName(url).Length) > 130)//重命名文件
                filepath = filepath + DateTime.Now.ToFileTime().ToString() + Path.GetExtension(url);
            else
                filepath = filepath + Path.GetFileName(url);
         
         
            try
            {
             
                WebClient mywebclient = new WebClient();
                mywebclient.Headers.Add("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36");
                mywebclient.Headers.Add("Accept-Language", "zh-cn");
                mywebclient.Headers.Add("Host", new Uri(url).Host);
                mywebclient.DownloadFile(url, filepath);
                return true;
            }
            catch (Exception ex)
            {

                Console.WriteLine(ex);

                if(File.Exists(filepath))
                File.Delete(filepath);//清理没成功的文件
                return false;
            }
        }
    }
}
